﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Wiwi.Models;
using Wiwi.ViewModels;
using System.Web.Security;
using System.Text.RegularExpressions;
namespace Wiwi.Controllers
{
    public class WantController : ApplicationController
    {
        //
        // GET: /Want/

        public ActionResult Index()
        {
            return View();
        }


        [Authorize]
        public ActionResult Pitch(string Wid)
        {
            WantSupplier supp = new WantSupplier();
            WiwiEntities1 db = new WiwiEntities1();
            Guid gu = new Guid(Wid);
            MembershipUser usr = Membership.GetUser();
            Guid gusr = new Guid(usr.ProviderUserKey.ToString());
            var wnt = (from wn in db.GetWants("ALL", null,null) where wn.WantID==gu select wn).ToList();
            ProfileView pv = new ProfileView();
            List<A_vWant> WntList = new List<A_vWant>();
            foreach (A_vWant wn in wnt)
            {
                A_vWant nw = new A_vWant();
                nw.FName = wn.FName;
                nw.Lname = wn.Lname;
                nw.Tags = wn.Tags;
                //nw.NewPitch = GetNewPitchForWant(wn.WantID, db);
                nw.Want_Wanter_RelID = wn.Want_Wanter_RelID;
                nw.UserID = wn.UserID;
                nw.IsCreator = wn.IsCreator;
                nw.WantbyUsr = CommonFunc.GetListOfMetoForWant(wn.WantID, db, wn.UserID);
                nw.WiwiDate = wn.WiwiDate;
                nw.WantDesc = wn.WantDesc;
                nw.IsClosed = wn.IsClosed;
                nw.WantID = wn.WantID;
                nw.PitchForSupplier = CommonFunc.GetWantpitchedForSupp(wn.Want_Wanter_RelID, gusr, db);
                WntList.Add(nw);
            }
            pv.Want = WntList;
            return View(pv);
        }
        [HttpPost]
        [Authorize]
        public ActionResult Pitch()
        {
            MembershipUser usr = Membership.GetUser();
            Guid gu = new Guid(usr.ProviderUserKey.ToString());
            WiwiEntities1 db = new WiwiEntities1();
            Guid GuWantID;
            if (Request.Form["HidPitch"] != null)
            {
                string relid = Request.Form["HidPitch"].ToString();
                string wText = Request.Form["T_" + relid].ToString();
                Guid relGu = new Guid(relid);
                A_Want_Wanter_Seller sel = new A_Want_Wanter_Seller();
                sel.WantWanterSellerID = Guid.NewGuid();
                sel.Want_Wanter_RelID = relGu;
                sel.UserSellerID = gu;
                sel.PitchDate = DateTime.Now;
                sel.pitchtext = wText;
                db.AddToA_Want_Wanter_Seller(sel);
                db.SaveChanges();
                A_Want_Wanter wnt =db.A_Want_Wanter.SingleOrDefault(c=> c.Want_Wanter_RelID == relGu);
                GuWantID = wnt.WantID;
                A_UserCreditConsumed cn = new A_UserCreditConsumed();
                cn.UsedFor = 1;
                cn.UserID = gu;
                cn.DateConsumed = DateTime.Now;
                cn.CreditConsumed = 3;
                db.AddToA_UserCreditConsumed(cn);
                db.SaveChanges();
                return RedirectToAction("Pitch", "Want", new { Wid = GuWantID.ToString() });
            }
            return RedirectToAction("Pitch");
        }
        [Authorize]
        public ActionResult UserPitch(string Wuid)
        {
            MembershipUser usr = Membership.GetUser();
            Guid gu = new Guid(Wuid);
            Guid gusr = new Guid(usr.ProviderUserKey.ToString());
            WiwiEntities1 db = new WiwiEntities1();
            UserPitches pites = new UserPitches();
            A_vWant wnt = db.A_vWant.SingleOrDefault(c => c.Want_Wanter_RelID == gu && c.UserID == gusr);
            pites.Want = wnt;
            var pit = (from pt in db.A_vUserPitches where pt.Want_Wanter_RelID == gu select pt).ToList();
            pites.Pitches = pit;
            return View(pites);
        }
        [HttpPost]
        [Authorize]
        public ActionResult UserPitch()
        {
            MembershipUser usr = Membership.GetUser();
            Guid gu = new Guid(usr.ProviderUserKey.ToString());
            WiwiEntities1 db = new WiwiEntities1();
            if (Request.Form["HidPitch"] != null)
            {
                Guid guW = new Guid(Request.Form["HidPitch"].ToString());
                A_Want_Wanter_Seller ws = db.A_Want_Wanter_Seller.SingleOrDefault(c => c.WantWanterSellerID == guW);
                if (Request.Form["HidPitchStatus"].ToString().ToUpper() == "ACCEPT")
                {
                    ws.PitchStatus = true;
                    ws.PitchStatusChangeDate = DateTime.Now;
                    db.SaveChanges();
                }
                if (Request.Form["HidPitchStatus"].ToString().ToUpper() == "REJECT")
                {
                    ws.PitchStatus = false;
                    ws.PitchStatusChangeDate = DateTime.Now;
                    db.SaveChanges();
                }
                return RedirectToAction("UserPitch", "Want", new { Wuid = ws.Want_Wanter_RelID.ToString() });
            }
            return RedirectToAction("../Home/Profile/");
        }
        [Authorize]
        public ActionResult WantComm(string Wid, string SuppID)
        {
            MembershipUser usr = Membership.GetUser();
            Guid gu = new Guid(Wid);
            Guid guSupp = new Guid(SuppID);
            Guid gusr = new Guid(usr.ProviderUserKey.ToString());
            WiwiEntities1 db = new WiwiEntities1();
            A_vWant wnt = db.A_vWant.SingleOrDefault(c => c.Want_Wanter_RelID == gu);
            WantCommunication wc = new WantCommunication();
            A_Want_Wanter_Seller sel = db.A_Want_Wanter_Seller.SingleOrDefault(c => c.Want_Wanter_RelID == gu && c.UserSellerID == guSupp);
            var comms = (from cm in db.A_vWantCommunication where cm.WantWanterSellerID == sel.WantWanterSellerID orderby cm.CommDate descending select cm).ToList();
            foreach (var cm in comms)
            {
                A_Want_SellerCommunication com = db.A_Want_SellerCommunication.SingleOrDefault(c => c.CommunicationID == cm.CommunicationID);
                if (com.UserID == gusr)
                {
                    com.IsRead = true;
                    db.SaveChanges();
                }
            }
            wc.seller = sel;
            wc.wnt = wnt;
            wc.comms = comms;
            return View(wc);
        }
        [Authorize]
        [HttpPost]
        public ActionResult WantComm()
        {
            MembershipUser usr = Membership.GetUser();
            Guid guWantWanterSeller = new Guid(Request.Form["SellerID"].ToString());
            Guid gu = new Guid(Request.Form["UserID"].ToString());
            Guid gusr = new Guid(usr.ProviderUserKey.ToString());
            WiwiEntities1 db = new WiwiEntities1();
            HttpPostedFileBase file = Request.Files["file1"];
            if (file != null)
            {
                if (file.ContentLength > 32000)
                {
                    ModelState.AddModelError("FileLength", "Selected file exceeded 3MB limit.");
                    Guid GuSupp = new Guid(Request.Form["SuppID"].ToString());
                    Guid guWantWanter = new Guid(Request.Form["Want_WanterID"].ToString());
                    A_vWant wnt = db.A_vWant.SingleOrDefault(c => c.Want_Wanter_RelID == guWantWanter);
                    WantCommunication wc = new WantCommunication();
                    A_Want_Wanter_Seller selE = db.A_Want_Wanter_Seller.SingleOrDefault(c => c.Want_Wanter_RelID == guWantWanter && c.UserSellerID == GuSupp);
                    var comms = (from cm in db.A_vWantCommunication where cm.WantWanterSellerID == selE.WantWanterSellerID orderby cm.CommDate descending select cm).ToList();
                    wc.seller = selE;
                    wc.wnt = wnt;
                    wc.comms = comms;
                    return View(wc);
                }
            }
            A_Want_Wanter_Seller sel = db.A_Want_Wanter_Seller.SingleOrDefault(c => c.WantWanterSellerID == guWantWanterSeller);
            A_Want_SellerCommunication com = new A_Want_SellerCommunication();
            com.Want_WanterSellerID = sel.WantWanterSellerID;
            com.CommDate = DateTime.Now;
            com.Comments = Request.Form["Reply"].ToString();
            com.FrmUserID = gusr;
            if (gu == gusr) // get supplier
            {
                com.UserID = sel.UserSellerID;
            }
            else //get buyer
            {
                A_Want_Wanter wt = db.A_Want_Wanter.SingleOrDefault(c => c.Want_Wanter_RelID == sel.Want_Wanter_RelID);
                com.UserID = wt.UserID;
            }
            db.AddToA_Want_SellerCommunication(com);
            db.SaveChanges();
            
            if (file != null)
            {
                if (file.ContentLength > 0)
                {
                    A_Attachment att = new A_Attachment();
                    byte[] bytes = new byte[file.ContentLength];
                    file.InputStream.Read(bytes, 0, file.ContentLength);
                    att.At_Byte = bytes;
                    att.At_Name = file.FileName;
                    att.At_ParentID = com.CommunicationID;
                    db.AddToA_Attachment(att);
                    db.SaveChanges();
                }
            }
            return RedirectToAction("../Home/Profile/");
        }
        
        private SearchView PerformSearch(string srch, WiwiEntities1 db)
        {
            List<A_vSearch> searches = new List<A_vSearch>();
            SearchView sv = new SearchView();
            bool DoubleQuote = false;
            bool OrFound = false;
            string SearchStr = "";
            foreach (char ch in srch)
            {
                char st = ch;
                if (st == '"')
                {
                    DoubleQuote = true;
                    break;
                }
            }
            if (DoubleQuote)
            {
                SearchStr = srch.Replace("\"", "");
                var srchs = db.A_Search("Exact", SearchStr);
                sv.SearchType = "Exact";
                foreach (A_vSearch sr in srchs)
                {
                    if (sr.ExpiryDate > DateTime.Now)
                    {
                        A_vSearch sr1 = new A_vSearch();
                        sr1.FName = sr.FName;
                        sr1.Lname = sr.Lname;
                        sr1.Tags = GetListOfTagsForWant(sr.WantID, db);
                        sr1.Want_Wanter_RelID = sr.Want_Wanter_RelID;
                        sr1.UserID = sr.UserID;
                        sr1.IsCreator = sr.IsCreator;
                        sr1.WantbyUsr = GetListOfMetoForWant(sr.WantID, db, sr.UserID);
                        sr1.WiwiDate = sr.WiwiDate;
                        sr1.WantDesc = sr.WantDesc;
                        sr1.IsClosed = sr.IsClosed;
                        sr1.WantID = sr.WantID;
                        A_vSearch srE = searches.SingleOrDefault(c => c.WantID == sr.WantID);
                        if (srE == null) searches.Add(sr1);
                    }
                }
            }
            if (!DoubleQuote)
            {
                if (srch.IndexOf(" OR") > 0 || srch.IndexOf(" or") > 0)
                {
                    srch = srch.Replace(" or", "");
                    srch = srch.Replace(" OR", "");
                    sv.SearchType = "or";
                    OrFound = true;
                    string[] arr = srch.Split(' ');
                    foreach (string str in arr)
                    {
                        if (str != "")
                        {
                            if (SearchStr == "") SearchStr = str + " OR ";
                            else SearchStr += str + " OR ";
                        }
                    }
                    SearchStr = SearchStr.Substring(0, SearchStr.Length - 4);
                    var srchs = db.A_Search("or", SearchStr);
                    foreach (A_vSearch sr in srchs)
                    {
                        if (sr.ExpiryDate > DateTime.Now)
                        {
                            A_vSearch sr1 = new A_vSearch();
                            sr1.FName = sr.FName;
                            sr1.Lname = sr.Lname;
                            sr1.Tags = GetListOfTagsForWant(sr.WantID, db);
                            sr1.Want_Wanter_RelID = sr.Want_Wanter_RelID;
                            sr1.UserID = sr.UserID;
                            sr1.IsCreator = sr.IsCreator;
                            sr1.WantbyUsr = GetListOfMetoForWant(sr.WantID, db, sr.UserID);
                            sr1.WiwiDate = sr.WiwiDate;
                            sr1.WantDesc = sr.WantDesc;
                            sr1.IsClosed = sr.IsClosed;
                            sr1.WantID = sr.WantID;
                            A_vSearch srE = searches.SingleOrDefault(c => c.WantID == sr.WantID);
                            if (srE == null) searches.Add(sr1);
                        }
                    }
                }
            }
            if (!DoubleQuote && !OrFound)
            {
                srch = srch.Replace(" and", "");
                srch = srch.Replace(" AND", "");
                sv.SearchType = "and";
                string[] arr = srch.Split(' ');
                foreach (string str in arr)
                {
                    if (str != "")
                    {
                        if (SearchStr == "") SearchStr = str + " and ";
                        else SearchStr += str + " and ";
                    }
                }
                SearchStr = SearchStr.Substring(0, SearchStr.Length - 5);
                var srchs = db.A_Search("and", SearchStr);
                foreach (A_vSearch sr in srchs)
                {
                    if (sr.ExpiryDate > DateTime.Now)
                    {
                        A_vSearch sr1 = new A_vSearch();
                        sr1.FName = sr.FName;
                        sr1.Lname = sr.Lname;
                        sr1.Tags = GetListOfTagsForWant(sr.WantID, db);
                        sr1.Want_Wanter_RelID = sr.Want_Wanter_RelID;
                        sr1.UserID = sr.UserID;
                        sr1.IsCreator = sr.IsCreator;
                        sr1.WantbyUsr = GetListOfMetoForWant(sr.WantID, db, sr.UserID);
                        sr1.WiwiDate = sr.WiwiDate;
                        sr1.WantDesc = sr.WantDesc;
                        sr1.IsClosed = sr.IsClosed;
                        sr1.WantID = sr.WantID;
                        A_vSearch srE = searches.SingleOrDefault(c => c.WantID == sr.WantID);
                        if (srE == null) searches.Add(sr1);
                    }
                }
            }
            sv.Searches = searches;
            sv.SearchTerm = SearchStr;
            return sv;
        }

        [HttpPost]
        public ActionResult Search()
        {
            WiwiEntities1 db = new WiwiEntities1();
            string srch ="";
            if(Request.Form["main-search"]!=null) srch = Request.Form["main-search"].ToString();
            else srch = Request.Form["hidSearchCounters"].ToString();
            SearchView sv = PerformSearch(srch, db);
            return View(sv);
        }
        public JsonResult SearchCount(string DT, string Term)
        {
            if (Term.Trim() != "")
            {
                string[] Arr = DT.Split(',');
                //lastdate = monthFunc + "/" + currentFunc.getDate() + "/" + currentFunc.getFullYear() + "/" + currentFunc.getHours() + "/" + currentFunc.getMinutes() + "/" + currentFunc.getSeconds();
                DateTime LastDT = new DateTime(int.Parse(Arr[2]), int.Parse(Arr[0]), int.Parse(Arr[1]), int.Parse(Arr[3]), int.Parse(Arr[4]), int.Parse(Arr[5]));
                WiwiEntities1 db = new WiwiEntities1();
                SearchView sv = PerformSearch(Term, db);
                var cnt = (from cn in sv.Searches where cn.WiwiDate > LastDT select cn.Want_Wanter_RelID).ToList();
                return Json(cnt.Count.ToString(), JsonRequestBehavior.AllowGet);
            }
            else
            {
                return Json("0", JsonRequestBehavior.AllowGet);
            }
        }

        private string GetListOfMetoForWant(Guid wntID, WiwiEntities1 db1, Guid UsrID)
        {
            string strRet = "";
            var UsrList = (from us in db1.A_Want_Wanter where us.WantID == wntID && us.UserID != UsrID && us.IsCreator == null select us.UserID).ToList();
            foreach (var usr in UsrList)
            {
                strRet += usr.ToString() + "?";
            }
            if (UsrList.Count > 0) strRet += "$" + UsrList.Count.ToString();
            return strRet;
        }
        private string GetListOfTagsForWant(Guid wntID, WiwiEntities1 db1)
        {
            string strRet = "";
            var wks = (from wk in db1.A_WantKeyword join wn in db1.A_KeyWord on wk.KeyWordID equals wn.KeywordID where wk.WantID == wntID select wn).ToList();
            foreach (var usr in wks)
            {
                strRet += usr.keyword + "?" + usr.KeywordID + "$ ";
            }
            return strRet;
        }
        [Authorize]
        public ActionResult Meto(string Wid)
        {
            MembershipUser usr = Membership.GetUser();
            Guid gu = new Guid(Wid);
            Guid gusr = new Guid(usr.ProviderUserKey.ToString());
            WiwiEntities1 db = new WiwiEntities1();
            var wu = from wn in db.A_Want_Wanter where wn.WantID == gu && wn.UserID == gusr && wn.IsClosed !=true select wn;
            if (!wu.Any())
            {
                A_Want_Wanter wusr = new A_Want_Wanter();
                wusr.Want_Wanter_RelID = Guid.NewGuid();
                wusr.IsClosed = false;
                wusr.IsCurrentOwner = false;
                wusr.UserID = gusr;
                wusr.WantID = gu;
                wusr.WiwiDate = DateTime.Now;
                wusr.ExpiryDate = DateTime.Now.AddDays(7);
                wusr.IsClosed = false;
                db.AddToA_Want_Wanter(wusr);
                db.SaveChanges();
                //ServiceReference1.Service1Client cli = new ServiceReference1.Service1Client();
                //cli.SendNotificationCompleted += new EventHandler<ServiceReference1.SendNotificationCompletedEventArgs>(cli_SendNotificationCompleted);
                //cli.SendNotificationAsync(gu);
            }
            return RedirectToAction("../Home/Profile/");
        }
        private void cli_SendNotificationCompleted(object sender, ServiceReference1.SendNotificationCompletedEventArgs args)
        {
            string str = args.Result.ToString();
        }
        
        [Authorize]
        public ActionResult CloseWant(string Wuid)
        {
            Guid gu = new Guid(Wuid);
            //Guid gusr = new Guid(Uid);
            WiwiEntities1 db = new WiwiEntities1();
            A_Want_Wanter wu = db.A_Want_Wanter.SingleOrDefault(c => c.Want_Wanter_RelID == gu);
            wu.IsClosed = true;
            wu.IsCurrentOwner = false;
            db.SaveChanges();
            var nxtWnts = (from wn in db.A_Want_Wanter where wn.WantID == wu.WantID && wn.IsClosed == false && wn.ExpiryDate > DateTime.Now orderby wn.ExpiryDate select wn).Take(1).ToList();
            if (nxtWnts.Any())
            {
                foreach (A_Want_Wanter wn in nxtWnts)
                {
                    A_Want_Wanter wntr = db.A_Want_Wanter.SingleOrDefault(c => c.Want_Wanter_RelID == wn.Want_Wanter_RelID);
                    wntr.IsCurrentOwner = true;
                    db.SaveChanges();
                }
            }
            return RedirectToAction("../Home/Profile/");
        }
        [HttpPost]
        [Authorize]
        public ActionResult SaveSearch(SearchView srchv)
        {
            if (srchv.SearchTerm != "")
            {
                WiwiEntities1 db = new WiwiEntities1();
                MembershipUser usr = Membership.GetUser();
                Guid gusr = new Guid(usr.ProviderUserKey.ToString());
                A_SavedSearches src = new A_SavedSearches();
                src.UserID = gusr;
                src.SearchSaveDate = DateTime.Now;
                src.SearchTerm = srchv.SearchTerm;
                src.SearchType = srchv.SearchType;
                db.AddToA_SavedSearches(src);
                db.SaveChanges();
            }
            return RedirectToAction("../Home/Profile/");
        }
        [Authorize]
        public ActionResult MySearches()
        {
            WiwiEntities1 db = new WiwiEntities1();
            MembershipUser usr = Membership.GetUser();
            Guid gu = new Guid(usr.ProviderUserKey.ToString());
            SearchView sv = new SearchView();
            List<A_vSearch> searches = new List<A_vSearch>();
            List<A_SavedSearches> savedSrches = new List<A_SavedSearches>();
            var savesr = from ss in db.A_SavedSearches where ss.UserID == gu select ss;
            sv.savedSrches = savesr.ToList();
            if (Request.QueryString["srchid"] != null)
            {
                long srid = long.Parse(Request.QueryString["srchid"].ToString());
                A_SavedSearches srcc = db.A_SavedSearches.SingleOrDefault(c => c.SearchID == srid);
                var srchs = db.A_Search(srcc.SearchType, srcc.SearchTerm);
                foreach (A_vSearch sr in srchs)
                {
                    if (sr.ExpiryDate > DateTime.Now)
                    {
                        A_vSearch sr1 = new A_vSearch();
                        sr1.FName = sr.FName;
                        sr1.Lname = sr.Lname;
                        sr1.Tags = GetListOfTagsForWant(sr.WantID, db);
                        sr1.Want_Wanter_RelID = sr.Want_Wanter_RelID;
                        sr1.UserID = sr.UserID;
                        sr1.IsCreator = sr.IsCreator;
                        sr1.WantbyUsr = GetListOfMetoForWant(sr.WantID, db, sr.UserID);
                        sr1.WiwiDate = sr.WiwiDate;
                        sr1.WantDesc = sr.WantDesc;
                        sr1.IsClosed = sr.IsClosed;
                        sr1.WantID = sr.WantID;
                        A_vSearch srE = searches.SingleOrDefault(c => c.WantID == sr.WantID);
                        if (srE == null) searches.Add(sr1);
                    }
                }
                sv.Searches = searches;
            }
            return View(sv);
        }
        [Authorize]
        public ActionResult CloseDeal(string SellerID)
        {
            Guid guSel = new Guid(SellerID);
            WiwiEntities1 db = new WiwiEntities1();
            A_Want_Wanter_Seller sel = db.A_Want_Wanter_Seller.SingleOrDefault(c => c.WantWanterSellerID == guSel);
            sel.CloseByUser = true;
            db.SaveChanges();
            return RedirectToAction("../Home/Profile/");
        }
        public ActionResult MatchWiwi(string Keyword)
        {
            WiwiEntities1 db = new WiwiEntities1();
            MembershipUser usr = Membership.GetUser();
            Guid gusr = new Guid(usr.ProviderUserKey.ToString());
            SupplierMatchingWiwi obj = new SupplierMatchingWiwi();
            var Lst = (from mt in db.A_vSupplierMatchingWiwi where mt.SupplierID == gusr select mt).ToList();
            obj.matches = Lst;
            if (Keyword != null)
            {
                int ikey = int.Parse(Keyword);
                A_WantKeyword wkw = db.A_WantKeyword.SingleOrDefault(c => c.Want_KeywordID == ikey);
                SearchView sv;
                A_KeyWord kw = db.A_KeyWord.SingleOrDefault(c => c.KeywordID == wkw.KeyWordID);
                if (wkw.SearchType == "A")
                {
                    sv = PerformSearch(kw.keyword, db);
                }
                else
                {
                    SearchView sv1 = new SearchView();
                    var Exact = (from sr in db.A_vSearch where sr.WantDesc.Contains(kw.keyword) select sr).ToList();
                    sv1.Searches = Exact;
                    sv = sv1;
                }
                List<A_vWant> WntList = new List<A_vWant>();
                foreach (var wn in sv.Searches)
                {
                    if (wn.UserID != gusr)
                    {
                        A_vWant nw = new A_vWant();
                        nw.FName = wn.FName;
                        nw.Lname = wn.Lname;
                        nw.Tags = wn.Tags;
                        nw.Want_Wanter_RelID = wn.Want_Wanter_RelID;
                        nw.UserID = wn.UserID;
                        nw.IsCreator = wn.IsCreator;
                        nw.WantbyUsr = CommonFunc.GetListOfMetoForWant(wn.WantID, db, wn.UserID);
                        nw.WiwiDate = wn.WiwiDate;
                        nw.WantDesc = wn.WantDesc;
                        nw.IsClosed = wn.IsClosed;
                        nw.WantID = wn.WantID;
                        nw.PitchForSupplier = CommonFunc.GetWantpitchedForSupp(wn.Want_Wanter_RelID, gusr, db);
                        WntList.Add(nw);
                    }
                }
                obj.Wants = WntList;
            }
            return View(obj);
        }
        public ActionResult CreditBuy()
        {
            return PartialView("CreditBuy", "1");
        }
        [HttpPost]
        public ActionResult CreditBuy(string selval)
        {
           
            string str = selval;

 

            WiwiEntities1 db = new WiwiEntities1();
            MembershipUser usr = Membership.GetUser();
            Guid gusr = new Guid(usr.ProviderUserKey.ToString());
            A_UserCredit cr = new A_UserCredit();
            cr.UserID = gusr;
            cr.Amount = int.Parse(str) / 2;
            cr.CreditPurchased = int.Parse(selval);
            cr.DatePurchased = DateTime.Now;
            db.AddToA_UserCredit(cr);
            db.SaveChanges();
            return new EmptyResult(); 
        }
        public ActionResult UserCreditbalance()
        {
            int bal = 0;
            WiwiEntities1 db = new WiwiEntities1();
            MembershipUser usr = Membership.GetUser();
            Guid gusr = new Guid(usr.ProviderUserKey.ToString());
            var recs = (from pr in db.A_UserCredit where pr.UserID == gusr select pr).Take(1);
            if (recs.Count() > 0)
            {
                var pur = (from pr in db.A_UserCredit where pr.UserID == gusr select pr.CreditPurchased).Sum();
                bal = pur;
            }
            var recs1 = (from cn in db.A_UserCreditConsumed where cn.UserID == gusr select cn.CreditConsumed).Take(1);
            if (recs1.Count() > 0)
            {
                var cns = (from cn in db.A_UserCreditConsumed where cn.UserID == gusr select cn.CreditConsumed).Sum();
                bal = bal - cns;
            }
            return Json(bal.ToString());
        }
    }
}
